package com.photoeditor.demo.util;

import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;

/**
 * 用于获取ImageView中显示的Drawable的大小
 */
public class ImageRectUtils {
	
	/**
	 * 获取某个View的正确的位置
	 * @param view
	 * @return
	 */
	public static RectF getViewRect(View view){
	    int vLeft, vTop;
		int location[] = new int[2];
		view.getLocationInWindow(location);
		vLeft = location[0];
		vTop = location[1];
		RectF mViewRect = new RectF(vLeft, vTop, vLeft + view.getWidth(), vTop + view.getHeight());
		return mViewRect;
	}
	
	/**
	 * 获取当前显示图片的宽高
	 * @return
	 */
	private static float[] getCurrentSize(ImageView view){
		float result[] = new float[]{0.0f, 0.0f};
		Drawable mDrawable = view.getDrawable();
		if(mDrawable == null){
			return result;
		}
		Rect r = mDrawable.getBounds();
		//真实宽高
		int w = r.width();
		int h = r.height();
		Matrix matrix1 = view.getImageMatrix();
		float[] values1 = new float[10];
		matrix1.getValues(values1);
		//当前显示的宽高
		
		result[0] = w * values1[0];
		result[1] = h * values1[4];
		return result;
	}
	
	/**
	 * 获取当前图片显示的Bounds 
	 * @return Rect
	 */
	public static RectF getDrawableRect(ImageView view){
		float size[] = getCurrentSize(view);
		float viewWidth = view.getWidth();
	    float Viewheight = view.getHeight();
	    
	    int bLeft, bTop;
	    int vLeft, vTop;
		int location[] = new int[2];
		view.getLocationInWindow(location);
		vLeft = location[0];
		vTop = location[1];
		
		float widthDistance, heightDistance;
		widthDistance = (viewWidth - size[0]) / 2;
		heightDistance = (Viewheight - size[1]) / 2;
		bLeft = (int)(vLeft + widthDistance + 0.5);
		bTop = (int)(vTop + heightDistance + 0.5);
		
		return new RectF(bLeft, bTop, (int)(bLeft + size[0] + 0.5f), (int)(bTop + size[1] + 0.5f));
	}
}
